package com.starnet.yarnmonitor.security.conf;

import com.starnet.yarnmonitor.security.custom.JwtAuthenticationProvider;
import com.starnet.yarnmonitor.security.custom.JwtFilterInvocationSecurityMetadataSource;
import com.starnet.yarnmonitor.security.custom.JwtUrlAccessDecisionManager;
import com.starnet.yarnmonitor.security.custom.JwtUserDetailsService;

import com.starnet.yarnmonitor.security.filter.JwtLoginFilter;
import com.starnet.yarnmonitor.security.filter.JwtTokenFilter;
import com.starnet.yarnmonitor.security.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    JwtLoginFailureHandler jwtLoginFailureHandler;
    @Resource
    JwtLoginSuccessHandler jwtLoginSuccessHandler;
    @Resource
    JwtAccessDeniedHandler jwtAccessDeniedHandler;
    @Resource
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Resource
    JwtFilterInvocationSecurityMetadataSource jwtFilterInvocationSecurityMetadataSource;
    @Resource
    JwtUrlAccessDecisionManager jwtUrlAccessDecisionManager;

    @Resource
    JwtAuthenticationProvider jwtAuthenticationProvider;
    @Resource
    JwtTokenFilter jwtTokenFilter;
    @Resource
    LogoutSuccessHandler jwtLogoutSuccessHandler;


    @Override
    public void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(jwtAuthenticationProvider);

    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 自定义登陆拦截器

        JwtLoginFilter jwtLoginFilter = new JwtLoginFilter();
        jwtLoginFilter.setFilterProcessesUrl("/user/login");
        jwtLoginFilter.setAuthenticationManager(authenticationManagerBean());
        jwtLoginFilter.setAuthenticationSuccessHandler(jwtLoginSuccessHandler);
        jwtLoginFilter.setAuthenticationFailureHandler(jwtLoginFailureHandler);


        http.authorizeRequests()
                .antMatchers("/v2/api-docs",
                        "/configuration/ui",
                        "/swagger-resources",
                        "/configuration/security",
                        "/swagger-ui.html",
                        "/webjars/**").permitAll();
        // 登陆验证信息
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setSecurityMetadataSource(jwtFilterInvocationSecurityMetadataSource);
                        object.setAccessDecisionManager(jwtUrlAccessDecisionManager);
                        return object;
                    }
                })
                //放行swagger
                .anyRequest().authenticated();


        // jwt 拦截器配置
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) //禁用session
                .and()
                .logout().logoutUrl("/user/logout").logoutSuccessHandler(jwtLogoutSuccessHandler)
                .and()
                .csrf().disable()
                .addFilterBefore(jwtTokenFilter, LogoutFilter.class)
                .addFilterBefore(jwtLoginFilter, JwtTokenFilter.class);// 添加拦截器
//                .addFilterAfter(jwtTokenFilter, JwtLoginFilter.class);
        // 权限处理信息
        http.exceptionHandling()
                //   用来解决认证过的用户访问无权限资源时的异常
                .accessDeniedHandler(jwtAccessDeniedHandler)
                // 用来解决匿名用户访问无权限资源时的异常
                .authenticationEntryPoint(jwtAuthenticationEntryPoint);

        http.cors();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


}